package com.jdone.compus.scheduling;

import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.service.OrderReconciliationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.*;
import java.time.format.DateTimeFormatter;

@Component
public class DailyOrderReconcileScheduler {
    private final Logger logger = LoggerFactory.getLogger(DailyOrderReconcileScheduler.class);

    private final OrderReconciliationService reconciliationService;

    // 从配置读取
    @Value("${recon.page-size:200}")
    private int pageSize;

    public DailyOrderReconcileScheduler(OrderReconciliationService reconciliationService) {
        this.reconciliationService = reconciliationService;
    }
//
//    // 程序启动后立即执行一次
//    @PostConstruct
//    public void init() {
//        logger.info("应用启动，开始执行历史对账任务...");
//        runHistoricalReconcile();
//    }

    @Scheduled(cron = "${recon.cron}", zone = "${recon.timezone}")
    public void runDailyReconcile() {
        try {
            // 时区：从配置的 zone 决定（占位符在注解已指定）
            // 这里为了构造时间范围，也使用同一时区
            ZoneId zone = ZoneId.of(System.getProperty("user.timezone", "Asia/Shanghai"));

            // 计算前一天的日期（在指定 zone 下）
            LocalDate todayInZone = LocalDate.now(zone);
            LocalDate targetDate = todayInZone.minusDays(1);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            String startTime = targetDate.atStartOfDay().format(dtf); // yyyy-MM-dd 00:00:00
            String endTime = targetDate.atTime(LocalTime.MAX).withNano(0).format(dtf); // yyyy-MM-dd 23:59:59

            ApiResponse resp = reconciliationService.reconcileAndSync(startTime, endTime, pageSize,true);

            if (resp != null && resp.isSuccess()) {
                logger.info("每日对账任务完成：{}", resp.getMessage());
            } else {
                logger.error("每日对账任务返回错误: {}", resp == null ? "null response" : resp.getMessage());
            }
        } catch (Exception ex) {
            logger.error("每日对账任务执行失败", ex);
        }
    }

    // 历史对账任务（从9月1日到今天）
    public void runHistoricalReconcile() {
        try {
            ZoneId zone = ZoneId.of(System.getProperty("user.timezone", "Asia/Shanghai"));

            // 计算日期范围：从9月1日到今天
            LocalDate startDate = LocalDate.of(2025, 9, 1);
            LocalDate endDate = LocalDate.now(zone);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            logger.info("开始执行历史对账任务，从 {} 到 {}", startDate, endDate);

            for (LocalDate currentDate = startDate;
                 !currentDate.isAfter(endDate);
                 currentDate = currentDate.plusDays(1)) {

                String startTime = currentDate.atStartOfDay().format(dtf);
                String endTime = currentDate.atTime(LocalTime.MAX).withNano(0).format(dtf);

                logger.info("执行对账任务，日期: {}", currentDate);

                ApiResponse resp = reconciliationService.reconcileAndSync(startTime, endTime, pageSize, true);

                if (resp != null && resp.isSuccess()) {
                    logger.info("对账任务完成 - 日期 {}: {}", currentDate, resp.getMessage());
                } else {
                    logger.error("对账任务返回错误 - 日期 {}: {}", currentDate,
                            resp == null ? "null response" : resp.getMessage());
                }

                // 可选：添加延迟避免请求过于频繁
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    logger.warn("对账任务延迟被中断");
                    break;
                }
            }

            logger.info("历史对账任务全部完成");

        } catch (Exception ex) {
            logger.error("历史对账任务执行失败", ex);
        }
    }
}

